#include "choosefrienddialog.h"

#include "Debug.h"

///
/// \brief 选择好友窗口中的一个 元素/好友项
///
ChooseFriendItem::ChooseFriendItem(ChooseFriendDialog* owner, const QString& userId,
                                   const QIcon& avatar, const QString &name, bool checked):
    m_owner(owner), m_avatar(avatar), m_userId(userId), m_name(name)
{
    //
    this->setFixedHeight(50);
    this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    this->setStyleSheet("QWidget:hover { background-color: #D9D8D8; }");

    QHBoxLayout* layout = new QHBoxLayout();
    layout->setContentsMargins(10, 0, 10, 0);
    layout->setSpacing(5);
    this->setLayout(layout);

    // 1.创建复选框
    m_checkBox = new QCheckBox();
    m_checkBox->setFixedSize(15, 15);
    m_checkBox->setChecked(checked);
    m_checkBox->setStyleSheet("QCheckBox { background-color: transparent; }"
                              "QCheckBox::indicator { width: 15px; height: 15px; image: url(:/resource/image/unchecked.png); }"
                              "QCheckBox::indicator:checked { image:url(:/resource/image/checked.png) }");

    // 2.创建头像
    QPushButton* avatarBtn = new QPushButton();
    avatarBtn->setFixedSize(30, 30);
    avatarBtn->setIconSize(QSize(30, 30));
    avatarBtn->setIcon(avatar);

    // 3.创建名字
    QLabel* nameLabel = new QLabel();
    nameLabel->setText(name);
    nameLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    nameLabel->setStyleSheet("QLabel { background-color: transparent; }");

    int MaxWidth = 200;  // 最大文字宽度
    QFontMetrics metrics(nameLabel->font());
    int totalWidth = metrics.horizontalAdvance(name);  // 实际文字长度
    if(totalWidth > MaxWidth){  // 如果过长，就截取一部分+省略号，具体算法可以画图便于理解
        QString tail = "...";
        int tailWidth = metrics.horizontalAdvance(tail);
        int availableSize = MaxWidth - tailWidth;
        QString truncatedName = name.left(name.length() * availableSize / totalWidth);
        nameLabel->setText(truncatedName + tail);
    }

    layout->addWidget(m_checkBox);
    layout->addWidget(avatarBtn);
    layout->addWidget(nameLabel);

    // 为choosefrienditem对象关联函数
    connect(m_checkBox, &QCheckBox::toggled, this, &ChooseFriendItem::toggleCheckBox);
    connect(m_owner, &ChooseFriendDialog::friendItemUnselect, m_checkBox, [=]{
        m_checkBox->setEnabled(false);
    });
}

void ChooseFriendItem::paintEvent(QPaintEvent *event)
{
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}

void ChooseFriendItem::toggleCheckBox(bool checked)
{
    if(checked){
        m_owner->addSelectFriend(m_userId, m_avatar, m_name);
    }else{
        m_owner->deleteSelectedFriend(m_userId);
    }
}

///
/// \brief 选择好友窗口
///
ChooseFriendDialog::ChooseFriendDialog(QWidget* parent):
    QDialog(parent), m_totalContainer(new QWidget()), m_selectedContainer(new QWidget())
{
    setWindowTitle("选择好友");
    setWindowIcon(QIcon(":/resource/image/logo.png"));
    setFixedSize(600, 400);
    setAttribute(Qt::WA_DeleteOnClose);
    setStyleSheet("QWidget { background-color: white; }"
                  "QScrollArea { border: none; }"
                  "QScrollBar:vertical { width: 2px; background-color: rgb(255, 255, 255); }"
                  "QScrollBar::handle:vertical {background-color: rgb(205, 205, 205);}"
                  "QScrollBar:horizontal { height: 0px;}");

    QHBoxLayout *layout = new QHBoxLayout();
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);
    setLayout(layout);

    // 左侧好友选择内容
    initLeftArea(layout);

    // 右侧显示好友列表
    initRightArea(layout);

    // 加载 好友列表
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    auto chat = dataCenter->findChatSessionBySessionId(dataCenter->getCurrentChatSessionId());
    auto friendList = dataCenter->getFriendList();
    for (auto it = friendList->begin(); it != friendList->end(); ++it) {
        if(it->m_userId == chat->m_message.m_sender.m_userId){
            addFriend(it->m_userId, it->m_avatar, it->m_nickName, true);
            addSelectFriend(it->m_userId, it->m_avatar, it->m_nickName);
            // emit friendItemUnselect(); // 这个是禁用选中的好友item 可以再次被选择
            LOG() << "进入一次";
        }else{
            addFriend(it->m_userId, it->m_avatar, it->m_nickName, false);
        }
    }
}

void ChooseFriendDialog::initLeftArea(QHBoxLayout *layout)
{
    QScrollArea* leftScrollArea = new QScrollArea();
    leftScrollArea->setWidgetResizable(true);
    layout->addWidget(leftScrollArea, 1);
    leftScrollArea->setWidget(m_totalContainer);

    QVBoxLayout* vlayout = new QVBoxLayout();
    m_totalContainer->setLayout(vlayout);
    vlayout->setContentsMargins(0, 0, 0, 0);
    vlayout->setSpacing(5);
    vlayout->setAlignment(Qt::AlignTop);

#if TEST_UI
    for (int i = 0; i < 15; ++i) {
        addFriend("1000"+QString::number(i+1), QIcon(":/resource/image/defaultAvatar2.jpg"), QString::number(i+1), false);
    }
#endif
}

void ChooseFriendDialog::initRightArea(QHBoxLayout *layout)
{
    // 1.建立布局
    QGridLayout* gLayout = new QGridLayout();
    gLayout->setContentsMargins(10, 10, 0, 10);
    gLayout->setVerticalSpacing(5);
    layout->addLayout(gLayout, 1);

    // 2.提示标签
    QLabel* tipLabel = new QLabel("选择联系人");
    tipLabel->setStyleSheet("QLabel { font-size:16px; font-weight: 700; }");

    // 3.滚动区好友内容
    QScrollArea* rightScrollArea = new QScrollArea();
    rightScrollArea->setWidgetResizable(true);

    rightScrollArea->setWidget(m_selectedContainer);
    QVBoxLayout* vlayout = new QVBoxLayout(); // 滚动区域的QWidget里用垂直布局
    vlayout->setContentsMargins(0, 0, 0, 0);
    vlayout->setSpacing(0);
    vlayout->setAlignment(Qt::AlignTop); // 设置靠上⽅对⻬
    m_selectedContainer->setLayout(vlayout);

    // 4.确认按钮
    QString style = "QPushButton {font-size: 12px; color: #27C160; background-color: #E9E9E9; border:none; border-radius: 5px;}"
                    "QPushButton:hover { background-color: #D2D2D2;}"
                    "QPushButton:pressed { background-color: #C6C6C6;}";
    QPushButton* okBtn = new QPushButton("完成");
    okBtn->setFixedHeight(30);
    okBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    okBtn->setStyleSheet(style);
    QPushButton* cancelBtn = new QPushButton("取消");
    cancelBtn->setStyleSheet(style);
    cancelBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    cancelBtn->setFixedHeight(30);

    gLayout->addWidget(tipLabel, 0, 0, 1, 9);
    gLayout->addWidget(rightScrollArea, 1, 0, 1, 9);
    gLayout->addWidget(okBtn, 2, 1, 1, 3);
    gLayout->addWidget(cancelBtn, 2, 5, 1, 3);

    connect(okBtn, &QPushButton::clicked, this, &ChooseFriendDialog::clickOkBtn);
    connect(cancelBtn, &QPushButton::clicked, this, &ChooseFriendDialog::close);
}

void ChooseFriendDialog::addFriend(const QString& userId, const QIcon& avatar, const QString &name, bool checked)
{
    ChooseFriendItem *item = new ChooseFriendItem(this, userId, avatar, name, checked);
    m_totalContainer->layout()->addWidget(item);
}

void ChooseFriendDialog::addSelectFriend(const QString& userId, const QIcon& avatar, const QString &name)
{
    ChooseFriendItem *item = new ChooseFriendItem(this, userId, avatar, name, true);
    m_selectedContainer->layout()->addWidget(item);
}

void ChooseFriendDialog::deleteSelectedFriend(const QString& userId)
{
    QVBoxLayout* layoutSelected = dynamic_cast<QVBoxLayout*>(m_selectedContainer->layout());

    // 遍历删除
    for(int i = layoutSelected->count()-1; i >= 0; i--) {
        QLayoutItem *child = layoutSelected->itemAt(i);
        // 判断是否符合删除条件
        if(child == nullptr || child->widget() == nullptr)
            continue;
        ChooseFriendItem* item = dynamic_cast<ChooseFriendItem*>(child->widget());
        if(item->getUserId() != userId){
            continue;
        }
        layoutSelected->removeItem(child);  // 删除元素
        item->deleteLater();    // 释放内存
    }

    // 同理，相同方法去掉左边的元素的勾选
    QVBoxLayout* totalLayout = dynamic_cast<QVBoxLayout*>(m_totalContainer->layout());
    for(int i = 0; i < totalLayout->count(); i++){
        auto child = totalLayout->itemAt(i);
        // 判断是否符合删除条件
        if(child == nullptr || child->widget() == nullptr)
            continue;
        ChooseFriendItem* item = dynamic_cast<ChooseFriendItem*>(child->widget());
        if(item->getUserId() != userId){
            continue;
        }

        item->getCheckBox()->setChecked(false);
    }

}

QList<QString> ChooseFriendDialog::generateMemberList()
{
    QList<QString> member;
    auto dataCenter = model::DataCenter::getInstance();
    const model::UserInfo* myself = dataCenter->getMyself();
    // 1. 把自己加进去
    if(myself){
        member.append(myself->m_userId);
    }

    // 2. 把选中的好友加进去
    QVBoxLayout* vlayout = dynamic_cast<QVBoxLayout*>(m_selectedContainer->layout());
    for (int i = 0; i < vlayout->count(); ++i) {
        auto* it = vlayout->itemAt(i);
        if (it == nullptr || it->widget() == nullptr) {
            continue;
        }
        ChooseFriendItem* friendItem = dynamic_cast<ChooseFriendItem*>(it->widget());
        member.append(friendItem->getUserId());
    }

    return member;
}

void ChooseFriendDialog::clickOkBtn()
{
    QList<QString> member = generateMemberList();
    if(member.size() < 2){
        LOG() << "群成员必须大于2两人";
        return;
    }
    auto dataCenter = model::DataCenter::getInstance();
    dataCenter->createGroupChatSessionAsync(member);
    this->accept();
}
